package top.codedance.iotp.tools.clientStatusMonitor.plugin;

import javax.media.*;
import java.io.File;

public class MyPlayer {
    private Player player; // 播放器对象
    private boolean isAutoStart;
    private boolean isAutoRestart;

    public MyPlayer(String mediaLocation, boolean isAutoStart, boolean isAutoRestart){
        this.isAutoStart = isAutoStart;
        this.isAutoRestart = isAutoRestart;
        File f = new File(mediaLocation);
        try {
            MediaLocator mediaLocator = new MediaLocator(f.toURI().toURL()); //媒体定位器
            player = Manager.createRealizedPlayer(mediaLocator); //得到播放器实例
            player.addControllerListener(new PlayerEventHandler()); //增加播放控制器
            player.realize();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    //播放器事件处理
    private class PlayerEventHandler extends ControllerAdapter {
        public void realizeComplete(RealizeCompleteEvent realizeDoneEvent) {
            player.prefetch(); //预取媒体数据
        }

        //完成预取媒体数据后，开始播放媒体
        public void prefetchComplete(PrefetchCompleteEvent prefetchDoneEvent) {
            if(isAutoStart) {
                player.start();
            }
        }

        //如果媒体播放完毕，重新设置媒体时间并停止媒体播放器
        public void endOfMedia(EndOfMediaEvent mediaEndEvent) {
            player.setMediaTime(new Time(0)); //重新设置媒体时间
            if(isAutoRestart) {
                player.start();
            }else{
                player.stop();
            }
        }
    }

    public void start(){
        player.start(); //开始播放媒体
    }

    public void stop(){
        player.setMediaTime(new Time(0)); //重新设置媒体时间
        player.stop(); // 停止媒体播放
    }
}
